<template>
    <div class='banner'>
        <div class="container">
            <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
                <el-form-item label="图片类型" prop="key_type">
                    <el-select v-model="queryParams.key_type" placeholder="图片类型" clearable size="small">
                        <el-option v-for="dict in typeList" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="图片标题" prop="key_title">
                    <el-input v-model="queryParams.key_title" placeholder="请输入菜单名称" clearable size="small" @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="跳转类型" prop="key_jump_type">
                    <el-select v-model="queryParams.key_jump_type" placeholder="跳转类型" clearable size="small">
                        <el-option v-for="dict in jumpTypeList" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
            <el-row :gutter="10" class="mb8">
                <el-col :span="22">
                    <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleBtn('add')" v-hasPermi="['customer:manage:add']">
                        新增</el-button>
                    <!-- curRow={};title = '新增商品';handleShow = 'add'; -->
                </el-col>
                <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
            <el-table border v-loading="loading" :data="tableList" ref="tableList" v-tableHeight :height="tableList&&tableList.length > 0 ? '900px' : '120px'">
                <el-table-column label="编号" align="center" prop="id" />
                <el-table-column label="图片类型" align="center" prop="type">
                    <template slot-scope="scope">
                        <span>
                            {{selectDictLabel(typeList, scope.row.type)}}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="图片" align="center" prop="url">
                    <template slot-scope="scope">
                        <div v-if="scope.row.url" class="img-list">
                            <el-image style="width: auto; height: 40px;" :src="scope.row.url" :preview-src-list="[scope.row.url]">
                            </el-image>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="图片标题" align="center" prop="title" />
                <el-table-column label="跳转类型" align="center" prop="jump_type">
                    <template slot-scope="scope">
                        <span>
                            {{selectDictLabel(jumpTypeList, scope.row.jump_type)}}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="跳转目标" align="center" prop="jump_target" />
                <el-table-column label="状态" align="center" prop="status">
                    <template slot-scope="scope">
                        <span>
                            {{selectDictLabel(statusList, scope.row.status)}}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" icon="el-icon-edit" @click="handleBtn('edit', JSON.parse(JSON.stringify(scope.row)))"
                            v-hasPermi="['basic:history:edit']">
                            编辑
                        </el-button>
                        <el-button v-if="scope.row.status==0" size="mini" type="text" @click="handleAble(scope.row)" v-hasPermi="['user:staff:stop']">停用
                        </el-button>
                        <el-button v-if="scope.row.status==1" size="mini" type="text" @click="handleAble(scope.row)" v-hasPermi="['user:staff:start']">启用
                        </el-button>
                        <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['basic:history:del']">
                            删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="pageCount>0" :pageCount="pageCount" :page.sync="queryParams.page" :limit.sync="queryParams.limit" @pagination="getList" />

            <el-dialog :title="title" visible v-if="handleShow == 'add'||handleShow == 'edit'" @close="close()" width="600px" append-to-body
                :close-on-click-modal="false">
                <el-form ref="form" :model="form" :rules="rules" label-width="120px" v-loading="formLoading">
                    <el-row>
                        <el-col :span="24">
                            <el-form-item prop="type" label="图片类型">
                                <el-select v-model="form.type" placeholder="请选择图片类型" clearable size="small" @change="changePic">
                                    <el-option v-for="dict in typeList" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item prop="title" label="图片标题">
                                <el-input style="width: 215px;" v-model="form.title" placeholder="请输入图片标题" clearable size="small" />
                            </el-form-item>
                        </el-col>

                        <el-col :span="24">
                            <el-form-item prop="jump_type" label="跳转类型">
                                <el-select v-model="form.jump_type" placeholder="请选择跳转类型" clearable size="small">
                                    <el-option v-for="dict in jumpTypeList" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24" v-if="form.jump_type>0">
                            <el-form-item prop="jump_target" label="跳转目标">
                                <el-input style="width: 215px;" v-model="form.jump_target" placeholder="请输入跳转目标" clearable size="small" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24" v-if="form.type||form.type=='0'">
                            <el-form-item label="banner图片" prop="url">
                                <el-upload class="avatar-uploader" :action="$uploadUrl" :show-file-list="false"
                                    :before-upload="beforeUpload" :on-success="handleAvatarSuccess">
                                    <img v-if="form.url" :src="form.url" class="avatar">
                                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                    <div slot="tip" class="el-upload__tip text-error" v-if="form.type=='0'">请上传图片尺寸为694*249的图片</div>
                                    <div slot="tip" class="el-upload__tip text-error" v-if="form.type=='3'">请上传图片尺寸为699*183的图片, 商城首页中部图片只能添加一次，多次添加小程序只会显示最后一次添加的图片（修改时也需编辑最后一次添加的）</div>
                                    <div slot="tip" class="el-upload__tip text-error"> 单文件大小请在1M以内,仅支持JPG、JPEG、PNG格式</div>
                                </el-upload>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="close()">取 消</el-button>
                    <el-button type="primary" @click="submit" :disabled="formLoading">确 定</el-button>
                </span>
            </el-dialog>
        </div>
    </div>
</template>
<script>
import throttle from 'lodash.throttle'
import { getBannerLists, setBannerInfo, getBannerInfo, setBannerStatus, delBanner } from "@/api/basic/banner.js"
import { departStatus } from "@/api/dictionary"
export default {
    name: '',
    components: {

    },
    data() {
        return {
            showSearch: true,
            loading: false,
            pageCount: 0,
            total: 0,
            queryParams: {
                page: 1,
                limit: 20,
                key_title: '',
                key_type: '',
                key_jump_type: '',
            },
            typeList: [
                { dictValue: 0, dictLabel: '商城项目首页图片' },
                { dictValue: 1, dictLabel: '商品分类页' },
                { dictValue: 3, dictLabel: '商城项目首页中部图片' },
            ],
            jumpTypeList: [
                { dictValue: 0, dictLabel: '不跳转' },
                { dictValue: 1, dictLabel: '跳转外链' },
                { dictValue: 2, dictLabel: '跳转商品详情' },
                // { dictValue: 3, dictLabel: '跳转服务详情' },
            ],
            tableList: [],
            title: "",
            handleShow: '',
            formLoading: false,
            form: {
                type: '',
                title: '',
                url: '',
                jump_type: '',
                jump_target: '',
            },
            rules: {
                type: [{ required: true, message: '请选择图片类型', trigger: 'blur' }],
                title: [{ required: true, message: '请输入图片标题', trigger: 'change' }],
                url: [{ required: true, message: '请选择上传图片', trigger: 'change' }],
                jump_type: [{ required: true, message: '请选择跳转类型', trigger: 'blur' }],
                jump_target: [{ required: true, message: '请输入跳转目标', trigger: 'change' }],
            },
            statusList: departStatus,
        }
    },
    // watch: {
    //     'form.type'(val) {
    //         console.log(val,'val')
    //     }
    // },
    created() {
        this.getList()
    },
    methods: {
        getList() {
            this.loading = true;
            getBannerLists(this.queryParams).then(res => {
                console.log(res.data, "res.data")
                this.tableList = res.data.lists;
                this.pageCount = res.data.pageCount;
                this.loading = false;
            });
        },
        handleBtn(type, row) {
            this.title = type == "add" ? "新增" : "编辑"
            if (row) {
                getBannerInfo({ banner_id: row.id }).then(res => {
                    console.log(res.data, "resss")
                    this.form = res.data
                    this.form.banner_id = this.form.id
                    delete this.form.id
                    delete this.form.sort
                    delete this.form.status
                })
            }
            this.handleShow = type;
        },

        handleAble(row) {
            let label = row.status == 0 ? '停用' : '启用';
            this.$confirm(`是否将“${row.title}”${label}?`, "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return setBannerStatus({ banner_id: row.id });
            }).then(() => {
                this.getList();
                this.msgSuccess(`${label}成功`);
            })
        },
        handleDelete(row) {
            this.$confirm('是否确认删除' + '"' + row.title + '"' + '?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return delBanner({ banner_id: row.id });
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            })
        },
        close() {
            this.form = {}
            this.handleShow = ""
        },
        handleQuery() {
            this.queryParams.page = 1;
            this.getList();
        },
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        changePic(e) {
            this.$set(this.form, "url", null)
        },
        beforeUpload(file, fileList) {
            return new Promise((resolve, reject) => {
                if (file.size / (1024 * 1024) > 1) {  // 限制文件大小
                    this.$message.warning(`当前限制文件大小不能大于1M`)
                    return reject(false)
                }
                if (this.form.type == '0') {
                    this.limitFileWH(694, 249, file).then((res) => {
                        file.isFlag = res
                        if (file.isFlag) {
                            return resolve(true)
                        } else {
                            return reject(false)
                        }
                    })
                } else if (this.form.type == '3') {
                    this.limitFileWH(699, 183, file).then((res) => {
                        file.isFlag = res
                        if (file.isFlag) {
                            return resolve(true)
                        } else {
                            return reject(false)
                        }
                    })
                } else {
                    resolve(true)
                }
            })
        },
        handleAvatarSuccess(res, file) {
            this.$set(this.form, 'url', res.data[0].fileurl)
        },
        submit: throttle(function () {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.formLoading = true;
                    setBannerInfo(this.form).then(res => {
                        this.msgSuccess("操作成功！");
                        this.close()
                        this.formLoading = false;
                        this.getList();
                    }).catch(() => {
                        this.formLoading = false;
                    })
                }
            })
        }, 1000, { trailing: false }),

    },
}

</script>
<style scoped lang='scss'>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100px;
    height: 100px;
}
.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    /* text-align: center;
    display: block !important; */
}
.avatar {
    width: 100px;
    height: 100px;
    display: block;
}
</style>